package com.netty.im.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2018/9/9/009.
 */
public class ImClient {
    static EventLoopGroup loopGroop = new NioEventLoopGroup();

    public static void connect() {
        try {
            Bootstrap bootStrap = new Bootstrap();
            bootStrap.group(loopGroop).channel(NioSocketChannel.class);
            bootStrap.handler(new ImClientInitializer());
            ChannelFuture channelFuture = bootStrap.connect("localhost", 8811);
            channelFuture.addListeners(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture f) throws Exception {
                    if (!f.isSuccess()) {
                        f.channel().eventLoop().schedule(new Runnable() {
                            @Override
                            public void run() {
                                connect();
                                System.out.println("重连..");
                            }
                        }, 2, TimeUnit.SECONDS);
                    } else {
                        System.out.println("成功!");
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        connect();

    }
}
